from mitmproxy import http
import json, time, os
import logging
import chardet

"""mitmdump -s save_responses.py"""

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取项目根目录
project_root = os.path.dirname(os.path.dirname(current_file_path))
# 保存响应数据的文件
output_file = project_root+"/interface/response/filtered_responses.json"

target_urls = [
    "https://api.example.com/endpoint1",
    "https://api.example.com/endpoint2",
    "https://api-v2.xdclass.net/api/account/v1/login",
    # 云机器列表
    "https://uphone-test.wo-adv.cn/bucp/servers/resource/instance/list",
    # 一键上云
    "https://uphone-test.wo-adv.cn/bucp/servers/resource/app/application-moving-list"
]

def response(flow: http.HTTPFlow):
    request_params=""
    for url in target_urls:
        if url in flow.request.pretty_url:
            if flow.response.status_code == 200:
                if flow.request.method == "POST":
                    try:
                        if not flow.request.content:
                            logger.warning("Request content is empty. Skipping modification.")
                            return
                        detected_encoding = chardet.detect(flow.request.content).get('encoding')
                        if not detected_encoding:
                            logger.warning("Encoding detection failed. Using default encoding utf-8.")
                            detected_encoding = 'utf-8'
                        request_params = flow.request.content.decode(detected_encoding)
                    except Exception as e:
                        logger.error(f"Error modifying POST request: {e}")
                elif flow.request.method == "GET":
                    try:
                        request_dic = dict(flow.request.query)
                        request_params = json.dumps(request_dic)  # 转换为JSON字符串
                    except Exception as e:
                        logger.error(f"Error modifying GET request: {e}")
                with open(output_file, "a") as f:
                    f.write(f"URL: {flow.request.pretty_url}\n")
                    f.write(f"方法: {flow.request.method}\n")
                    f.write(f"传递参数: {request_params}\n")
                    f.write(f"Response: {flow.response.text}\n")
                    f.write("-" * 50 + "\n")
                print(f"Captured response from {flow.request.pretty_url}")